<?php
namespace app\erp_meixingtiyu\logic;

use app\erp_meixingtiyu\model\Course as CourseModel;
use app\erp_meixingtiyu\model\CourseLesson as CourseLessonModel;
use app\erp_meixingtiyu\model\CourseLessonClockIn as CourseLessonClockInModel;
use app\erp_meixingtiyu\model\CourseOrder as CourseOrderModel;

class Course
{
    public function getList()
    {
      $list = (new CourseModel)->getListByPaginate();
      return $list->toArray();
    }

    public function getOrderListByDate($dateArr)
    {
      [$startDate, $endDate] = $dateArr;
      $endDateArr = explode('-', $endDate);
      $endDateArr[2] = (int)$endDateArr[2] + 1;
      $endDate = implode('-', $endDateArr);
      $list = CourseOrderModel::getListByDate($startDate, $endDate);
      return $list->toArray();
    }

    public function addCourse($data)
    {
      (new CourseModel)->createCourse($data);
    }

    public function editCourse($data)
    {
      (new CourseModel)->updateCourse($data);
    }

    public function deleteCourse($courseId)
    {
      // 如果该课程有学员报名了，则不能删除
      $studentList = (new CourseOrderModel)->getAllStudentsByCourseId($courseId);
      if(!$studentList->isEmpty()) {
        throwError('该课程有学员已报名，不能删除');
      }
      (new CourseModel)->destoryCourse($courseId);
    }

    public function getOrderList() 
    {
      $list = CourseOrderModel::getList();
      return $list->toArray();
    }

    public function getStudentList($courseId)
    {
      $list = (new CourseOrderModel)->getAllStudentsByCourseId($courseId);
      // 获取所有课程
      $lessons = (new CourseLessonModel)->getLessonsByCourseId($courseId);
      $lesson_ids = [];
      foreach($lessons as $lesson) {
        array_push($lesson_ids, $lesson->lesson_id);
      }

      // 获取该课程的用户集合
      $userCollections = $list->map(function($order) {
        return $order->user;
      });
      foreach($userCollections as $user) {
        $userClockInRecords = $this->getClockInRecordByUserId($lesson_ids, $user->user_id);
        $user->userClockInRecords = $userClockInRecords;
        $user->allLessons = $lessons;
      }
      return $userCollections->toArray();
    }

    // 查找单个学员的指定课程的签到记录
   public function getClockInRecordByUserId($lesson_ids, $userId)
   {
      
      $clockInRecords = (new CourseLessonClockInModel)->getRecordsByUserId($lesson_ids, $userId);
      return $clockInRecords;
   }
}
